<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="canvas" width="1000" height="800"></canvas>
  </body>
</html>
<script src="./tool.js"></script>
<script>
  const canvas = document.getElementById("canvas");
  const cxt = canvas.getContext("2d");

  /*
     利用translate进行平移，小球的平移，
     利用save，restore来进行状态的保存与恢复
     匀速直线运动
     实现带有角度的运动
     实现跟随鼠标的移动：只需要计算出角度 Math.atan2
    */

  //  清除画布
  function clearCanvas() {
    cxt.clearRect(0, 0, canvas.width, canvas.height);
  }

  // 画小球  中心点坐标 半径
  function drawBall(x, y, r) {
    cxt.save();
    cxt.translate(x, y);
    cxt.beginPath();
    cxt.arc(0, 0, r, (Math.PI / 180) * 0, (Math.PI / 180) * 360, true);
    cxt.closePath();
    cxt.restore();
    cxt.strokeStyle = "red";
    cxt.stroke();
  }
  let speed = 1;
  let angle = 90,oldAngle = 90
  const ball = { x: 100, y: 100 };
  const mouse = tools.getMouse(canvas);
  let easing = 0.02; // 如果缓动系数很大的话 直接出现的效果就是移动的
  let spring = 0.02;
  let vx = 0,
    vy = 0;

  function frame() {
    window.requestAnimationFrame(frame);
    clearCanvas();
    if (vy || vy) {
      vx = speed * Math.cos(angle);
      vy = speed * Math.sin(angle);
    }
    else{
      vx = vx * Math.cos(angle);
      vy = vy * Math.sin(angle);
    }

    // ball.x +=vx
    // ball.y +=vy
    // 对于缓动动画
    // vx = (mouse.x - ball.x) * easing;
    // vy = (mouse.y - ball.y) * easing;

    // 弹性动画

    let vxa = (mouse.x - ball.x) * spring;
    let vya = (mouse.y - ball.y) * spring;
    vx += vxa;
    vy += vya;

    ball.x += vx;
    ball.y += vy;

    cxt.translate(vx, vy); // save与restore可以成套的使用的
    drawBall(100, 100, 20);

    // 采用平移的方法 现在是没有办法知道当前球心的坐标的 还是需要进行不断的累计的
    angle = Math.atan2(mouse.y - ball.y, mouse.x - ball.x);
    console.log("angle", angle);
  }
  frame();
</script>
